import template from './template';
export default class BaseContext {
  constructor(app, options = {}) {
    this.createContext(app)
    // 配置挂载
    this.options = options;
  }

  createContext(app) {
    // 挂载公共工具类
    this.app = app;
    this.util = app.util;
    this.request = app.request;
    this.logger = app.logger;

    this.store = app.store;
    this.state = app.state;

    this.config = app.options; // 应用配置
    this.container = app.container;
    // 模板
    this.template = Object.assign(template, app.options.template);
  }

  get scrollContainer() {
    return this.app.scrollContainer;
  }
  get comicInfo() {
    return this.state.comic;
  }
  get currentChapter() {
    const comicInfo = this.state.comic;
    if (comicInfo) {
      return comicInfo.chapterMap[comicInfo.currentChapterId];
    } else return Object.create(null);
  }

  // 发送事件
  emit(event, ...args) {
    if (Array.isArray(event)) {
      event.forEach((evt, index) => {
        let evtArgs = [];
        if (args && Array.isArray(args[0])) {
          evtArgs = args[0][index]
          if (!Array.isArray(evtArgs)) {
            evtArgs = [evtArgs]
          }
        }
        this.app.emit(evt, ...evtArgs);
      });
    } else {
      this.app.emit(event, ...args);
    }
  }

  // 监听事件
  listener(...args) {
    let [type, event, callback, context] = args, observer = Object.create(null);
    const errMsg = new Error('抱歉，传入的listener参数不正确');
    switch (args.length) {
      case 2:
        {
          if (typeof event !== 'object') throw errMsg;
          observer = event;
        }
        break;
      case 3:
        {
          if (typeof event !== 'string' || typeof callback !== 'function') throw errMsg;
          observer[event] = callback;
        }
        break;
      default:
        {
          if (typeof type === 'object') {
            observer = type;
            type = 'on';
          } else if (typeof type !== 'string') {
            throw errMsg;
          }
        }
    }
    Object.keys(observer).forEach(item => {
      this.app[type](item, observer[item], context);
    })
  }
}
